package com.myblog.controller;

import com.myblog.Utils.BeanCopyUtils;
import com.myblog.domain.GlobalResponse;
import com.myblog.domain.Vo.CategoryVo;
import com.myblog.domain.dto.CategoryDto;
import com.myblog.domain.entity.Category;
import com.myblog.domain.entity.enums.GlobalResponseEnum;
import com.myblog.services.CategoryService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/content/category")
public class CategoryController {

    @Resource
    CategoryService categoryService;


    @GetMapping("/listAllCategory")
    public GlobalResponse getAllCategory(){
        return categoryService.getAllCategoryList();
    }

    @PreAuthorize("@ps.hasPermission('content_category_export')")
    @GetMapping("/export")
    public void export(HttpServletResponse response){
        categoryService.AllListToExcel(response);
    }

    @GetMapping("/list")
    public GlobalResponse getCategoryList(Integer pageNum,Integer pageSize,String name,String status){
        return categoryService.getList(pageNum,pageSize,name,status);
    }

    @PostMapping()
    public GlobalResponse addCategory(@RequestBody CategoryDto categoryDto){
        return categoryService.addCategory(categoryDto);
    }
    @GetMapping("/{id}")
    public GlobalResponse getCategory(@PathVariable Long id){
        Category category = categoryService.getById(id);
        CategoryVo categoryVo = BeanCopyUtils.copyBean(category, CategoryVo.class);
        return GlobalResponse.ok(categoryVo);
    }
    @PutMapping()
    public GlobalResponse updateCategory(@RequestBody CategoryVo categoryVo){
        Category category = BeanCopyUtils.copyBean(categoryVo, Category.class);
        if(categoryService.updateById(category)){
            return GlobalResponse.ok();
        }
        return GlobalResponse.error(GlobalResponseEnum.ID_NO_EXIST);
    }
    @DeleteMapping("/{id}")
    public GlobalResponse deleteCategory(@PathVariable Long id){
        if (categoryService.removeById(id)){
            return GlobalResponse.ok();
        }
        return GlobalResponse.error(GlobalResponseEnum.ID_NO_EXIST);
    }

}

